package com.middlegroup.pay.bind;


import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


/**
 * @author pc
 */
public class SessionMerchantCodeArgumentResolver implements
		HandlerMethodArgumentResolver {

	@SuppressWarnings("rawtypes")
	protected void raiseMissingParameterException(String paramName,
			Class paramType) throws Exception {
		throw new IllegalStateException("Missing parameter '" + paramName
				+ "' of type [" + paramType.getName() + "]");
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		SessionMerchantCode requestParamAnnot = parameter
				.getParameterAnnotation(SessionMerchantCode.class);
		if (null != requestParamAnnot) {
			return true;
		}

		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
								  ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
								  WebDataBinderFactory binderFactory) throws Exception {

		SessionMerchantCode requestParamAnnot = parameter
				.getParameterAnnotation(SessionMerchantCode.class);
		HttpServletRequest httpRequest = (HttpServletRequest) webRequest
				.getNativeRequest();
		String result = (String) httpRequest.getAttribute("merchantCode");

		if (result == null && requestParamAnnot.required()) {
			raiseMissingParameterException("merchantCode", parameter.getParameterType());
		} else {
			return result;
		}

		return null;
	}
}
